package com.freesky.web.manager.aop;

import com.freesky.common.annotation.SystemLogAnno;
import com.freesky.common.dao.entity.SystemLog;
import com.freesky.common.utils.ThreadPoolUtil;
import com.freesky.common.utils.TimeUtil;
import com.freesky.web.manager.shiro.CurrentUser;
import com.freesky.web.manager.util.SystemUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * Spring AOP实现日志管理
 *
 * @author Freesky
 */
@Aspect
@Component
@Slf4j
public class SystemLogAspect {


    private static final ThreadLocal<Date> beginTimeThreadLocal = new NamedThreadLocal<Date>("ThreadLocal beginTime");


    @Autowired(required = false)
    private HttpServletRequest request;

    /**
     * Controller层切点,注解方式
     */
    @Pointcut("@annotation(com.freesky.common.annotation.SystemLogAnno)")
    public void controllerAspect() {
        log.info("========controllerAspect===========");
    }


    /**
     * 前置通知 (在方法执行之前返回)用于拦截Controller层记录用户的操作的开始时间
     *
     * @param joinPoint 切点
     * @throws InterruptedException
     */
    @Before("controllerAspect()")
    public void doBefore(JoinPoint joinPoint) throws InterruptedException {

        //线程绑定变量（该数据只有当前请求的线程可见）
        Date beginTime = new Date();
        beginTimeThreadLocal.set(beginTime);
    }


    /**
     * 后置通知(在方法执行之后返回) 用于拦截Controller层操作
     *
     * @param joinPoint 切点
     */
    @After("controllerAspect()")
    public void after(JoinPoint joinPoint) {
        boolean authenticated = SecurityUtils.getSubject().isAuthenticated();
        if (!authenticated) {
            log.info("未登录");
            return;
        }
        String username = CurrentUser.INSTANCE.getUser().getUsername();

        if (null != username) {
            SystemLog systemLog = new SystemLog();
            systemLog.setUsername(username);
            systemLog.setOperation(getMethodDescription(joinPoint));
            systemLog.setIp(SystemUtil.getIpAddr(request));
            //请求耗时
            long beginTime = beginTimeThreadLocal.get().getTime();
            long endTime = System.currentTimeMillis();
            Long responseTime = endTime - beginTime;
            systemLog.setResponseTime(responseTime.intValue());
            systemLog.setCreateTime(TimeUtil.getDateTimeNow());
            //调用线程保存至数据库
            ThreadPoolUtil.getPool().execute(new SaveSystemLogThread(systemLog));
        }
    }


    /**
     * 保存日志
     */
    private static class SaveSystemLogThread implements Runnable {
        private SystemLog systemLog;

        SaveSystemLogThread(SystemLog systemLog) {
            this.systemLog = systemLog;
        }

        @Override
        public void run() {
            systemLog.insert();
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param joinPoint 切点
     * @return 方法描述
     * @throws Exception
     */
    public static String getMethodDescription(JoinPoint joinPoint) {
        //获取目标类名
        String targetName = joinPoint.getTarget().getClass().getName();
        //获取方法名
        String methodName = joinPoint.getSignature().getName();
        //获取相关参数
        Object[] arguments = joinPoint.getArgs();
        //生成类对象
        Class targetClass = null;
        try {
            targetClass = Class.forName(targetName);
        } catch (ClassNotFoundException e) {
            log.error("找不到该类", e);
            e.printStackTrace();
        }
        //获取该类中的方法
        Method[] methods = targetClass.getMethods();

        String description = "";

        for (Method method : methods) {
            if (!method.getName().equals(methodName)) {
                continue;
            }
            Class[] clazzs = method.getParameterTypes();
            if (clazzs.length != arguments.length) {
                //比较方法中参数个数与从切点中获取的参数个数是否相同，原因是方法可以重载哦
                continue;
            }
            description = method.getAnnotation(SystemLogAnno.class).description();
        }
        return description;
    }
}
